package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.bson.Document;

import com.sentiment.bean.LogOperation;
import com.sentiment.bean.OperationInfo;
import com.sentiment.database.bean.Role;
import com.sentiment.database.bean.User;
import com.sentiment.database.bean.UserInfo;
import com.sentiment.database.bean.UserLog;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.shiro.ActiveUser;
import com.sentiment.tools.Format;
import com.sentiment.tools.Generator;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String methodName = request.getParameter("method");
		try{
			Method method = getClass().getMethod(methodName, 
					HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 验证用户名是否可用
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void CheckUserName(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String info = "";
		String username = request.getParameter("username");
		User user = new User();
		user = user.getUserByUserCode(username);
		if(user == null)
			info = "false";
		else
			info = "true";
			
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(info);
		
	}
	
	/**
	 * 验证手机号是否可用
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void CheckPhoneNum(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String info = "";
		String phonenum = request.getParameter("phonenum");
		
		UserInfo userinfo = new UserInfo();
		userinfo.setPhonenumb(phonenum);
		DbUtil db = new DbUtil();
		db.openConnection(UserInfo.dbName, UserInfo.collection);
		Document t = db.query(userinfo.toDocument(), new String[] {"phonenumb"});
		db.closeConnection();

		if(t == null)
			info = "false";
		else
			info = "true";
			
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(info);
		
	}
	
	/**
	 * 新建管理员方法
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void NewAdmin(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String username = request.getParameter("username");
		String phonenumb = request.getParameter("phonenumb");
		//String password = request.getParameter("password");
		String idcardnumb = request.getParameter("idcardnumb");
		String sex = request.getParameter("sex");
		System.out.println(username);
		String password = "111111";
		
		//盐
		String salt = Generator.getRandomString(5);
		//散列次数
		int hashIterations = 1;
		Md5Hash md5Hash = new Md5Hash(password, salt, hashIterations);		
		String password_md5 =  md5Hash.toString();
		
		//User表
		User user = new User(null, username, password_md5, salt, false);
		DbUtil db = new DbUtil();
		db.openConnection(User.dbName, User.collection);
		String user_id = db.insertGetId(user.toDocument()).toString();
		db.closeConnection();
		//User添加角色
		Role role = new Role();
		role = role.getRoleByRoleName("admin");
		user = user.getUserByUser_id(user_id);
		user.addRole(role);
		//UserInfo表
		UserInfo info = new UserInfo(sex, Format.string2Date(Format.GetBirth(idcardnumb), 3), phonenumb, null, idcardnumb, user_id, null, null, null, null, 0.0, Format.date2String(new Date(), 3));
		db.openConnection(UserInfo.dbName, UserInfo.collection);
		db.insert(info.toDocument());
		db.closeConnection();
		//UserLog表
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		UserLog log = new UserLog(user_id, Format.date2String(new Date(), 3), LogOperation.register, session.getHost());
		db.openConnection(UserLog.dbName, UserLog.collection);
		db.insert(log.toDocument());
		db.closeConnection();
		
		String jsonStr = "{\"info\":" + "\"" + OperationInfo.OperSuccess + "\"" +"}";

		System.out.println(jsonStr);
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}
	

	/**
	 * 普通用户注册方法
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void Register(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String username = request.getParameter("username");
		String phonenumb = request.getParameter("phonenumb");
		String password = request.getParameter("password");
		String idcardnumb = request.getParameter("idcardnumb");
		String email = request.getParameter("email");		
		String sex = request.getParameter("sex");
		System.out.println(username);
		
		//盐
		String salt = Generator.getRandomString(5);
		//散列次数
		int hashIterations = 1;
		Md5Hash md5Hash = new Md5Hash(password, salt, hashIterations);		
		String password_md5 =  md5Hash.toString();
		
		//User表
		User user = new User(null, username, password_md5, salt, false);
		DbUtil db = new DbUtil();
		db.openConnection(User.dbName, User.collection);
		String user_id = db.insertGetId(user.toDocument()).toString();
		db.closeConnection();
		//User添加角色
		Role role = new Role();
		role = role.getRoleByRoleName("nopay");
		user = user.getUserByUser_id(user_id);
		user.addRole(role);
		//UserInfo表
		UserInfo info = new UserInfo(sex, Format.string2Date(Format.GetBirth(idcardnumb), 3), phonenumb, email, idcardnumb, user_id, null, null, null, null, 0.0, Format.date2String(new Date(), 3));
		db.openConnection(UserInfo.dbName, UserInfo.collection);
		db.insert(info.toDocument());
		db.closeConnection();	
		
		//登陆
		String error = null;
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		//UserLog表
		UserLog log = new UserLog(user_id, Format.date2String(new Date(), 3), LogOperation.register, session.getHost());
		db.openConnection(UserLog.dbName, UserLog.collection);
		db.insert(log.toDocument());
		db.closeConnection();
		
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
            subject.login(token);
		}catch (Exception e) {
            error = e.toString();
		}
	
		if(error != null){//登陆出现错误
			request.setAttribute("errorInfo", error);
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}else {//登录成功
			//设置session有效时间
			
		//    	//测试用  8秒失效
		//    	session.setTimeout(8000);
			ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
			log = new UserLog(activeUser.getUser_id(), Format.date2String(new Date(), 3), LogOperation.login, session.getHost());
			db.openConnection(UserLog.dbName, UserLog.collection);
			db.insert(log.toDocument());
			db.closeConnection();
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}
		
	}
	
}
